﻿// *----------------------------------------------------------------
// Copyright (C) 2017 通通优品
// 版权所有。
// 
// 类名：ApiContext.cs
// 功能描述：TongTongMall.MallWeb.ApiRepository
// 
// Create User：jym 2017/02/28
// 
// Edit User：UserName,EditTime
// Describe：Describe
// ----------------------------------------------------------------*/
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using TongTongMall.Dependecy;
using TongTongMall.MallWeb.ApiRepository.Domain.Exceptions;
using TongTongMall.MallWeb.ApiRepository.Domain.Logger;

namespace TongTongMall.MallWeb.ApiRepository.Domain
{
    public class ApiContext : IApiContext, ISingletonDependency
    {
        private readonly IApiHttpClient _apiHttpClient;

        public ApiContext(IApiHttpClient apiHttpClient)
        {
            this._apiHttpClient = apiHttpClient;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <param name="httpContents"></param>
        /// <param name="tResultType"></param>
        /// <returns></returns>
        public async Task<TResult> PostAsync<TResult>(string url, IDictionary<string, StringContent> httpContents, Type tResultType = null) where TResult : class
        {
            var methodRunTime = new Stopwatch();
            methodRunTime.Start();
            using (var response = await _apiHttpClient.PostAsync(new Uri(url), httpContents))
            {
                methodRunTime.Stop();
                if (!response.IsSuccessStatusCode)
                {
                    throw new ApiRequestException(response.StatusCode, url, "报错URL地址：" + url + "! 报错参数StatusCode: " + response.StatusCode + ",报错类型: " + response.ReasonPhrase);
                }
                else
                {
                    var ts = methodRunTime.Elapsed;
                    ApiLogHelper.Logger.Debug($"\r\n{url}\r\n{response.IsSuccessStatusCode}\r\n方法响应时间为：{ts.Hours:00}:{ts.Minutes:00}:{ts.Seconds:00}.{ts.Milliseconds / 10:00}\r\n{JsonConvert.SerializeObject(httpContents)}\r\n{JsonConvert.SerializeObject(response)}");
                }
                if (tResultType == typeof(string))
                {
                    var result = await response.Content.ReadAsStringAsync();
                    return result as TResult;
                }
                else
                {
                    var ajaxResponse = JObject.Parse(await response.Content.ReadAsStringAsync()).ToObject<TResult>();

                    return ajaxResponse;
                }
            }
        }

        public async Task<TResult> PostAsync<TResult>(string url, int? timeout = null) where TResult : class, new()
        {
            return await PostAsync<TResult>(url, timeout: timeout);
        }
        

        public async Task<TResult> PostAsync<TResult>(string url, object input, int? timeout = null) where TResult : class, new()
        {
            var methodRunTime = new Stopwatch();
            methodRunTime.Start();
            using (var response = await _apiHttpClient.PostAsync(url, input, timeout))
            {
                methodRunTime.Stop();
                if (!response.IsSuccessStatusCode)
                {
                    throw new ApiRequestException(response.StatusCode, url, "报错URL地址：" + url + "! 报错参数StatusCode: " + response.StatusCode + ",报错类型: " + response.ReasonPhrase);
                }
                else
                {
                    TimeSpan ts = methodRunTime.Elapsed;
                    ApiLogHelper.Logger.Debug($"\r\n{url}\r\n{response.IsSuccessStatusCode}\r\n方法响应时间为：{ts.Hours:00}:{ts.Minutes:00}:{ts.Seconds:00}.{ts.Milliseconds / 10:00}\r\n{JsonConvert.SerializeObject(input)}\r\n{JsonConvert.SerializeObject(response)}");
                }
                var ajaxResponse = JObject.Parse(await response.Content.ReadAsStringAsync()).ToObject<TResult>();

                return ajaxResponse;
            }

        }
    }
}
